"""
Example demonstrating AIBrowser capabilites with AgentBay SDK.
This example shows how to use AIBrowser to visit aliyun.com, including:
- Create AIBrowser session
- Use playwright to connect to AIBrowser instance through CDP protocol
- Utilize playwright to visit aliyun.com
"""

import os
from datetime import datetime
import asyncio
from typing import Any, Optional, List
import json
from agentbay import AgentBay
from agentbay.session_params import CreateSessionParams
from agentbay.browser.browser import BrowserOption

from agentbay.browser.browser_agent import ActOptions, ObserveOptions, ExtractOptions

from playwright.async_api import async_playwright

from pydantic import BaseModel, Field, HttpUrl, field_validator
from urllib.parse import urljoin


class ProductInfo(BaseModel):
    name: str
    price: str
    link: Optional[HttpUrl] = Field(
        None, description="The absolute URL to the product's detail page."
    )

    @field_validator("link", mode="before")
    @classmethod
    def validate_and_clean_link(cls, v: Any) -> Optional[str]:
        if not isinstance(v, str) or not v:
            return None

        if v.startswith("/"):
            base_url = "https://www.casetify.cn"
            return urljoin(base_url, v)

        if v.startswith("#"):
            return None

        return v


class InspectionResult(BaseModel):
    products: List[ProductInfo]


class InspectionResult(BaseModel):
    products: List[ProductInfo] = Field(..., description="A list of all products.")


async def main():
    # Get API key from environment variable
    api_key = "akm-ef2137ed-2130-4282-bfd3-f6fb79493ce8"
    if not api_key:
        print("Error: AGENTBAY_API_KEY environment variable not set")
        return

    # Initialize AgentBay client
    print("Initializing AgentBay client...")
    agent_bay = AgentBay(api_key=api_key)

    # Create a session
    print("Creating a new session...")
    params = CreateSessionParams(
        image_id="browser_latest",  # Specify the image ID
    )
    session_result = agent_bay.create(params)

    if session_result.success:
        session = session_result.session
        print(f"Session created with ID: {session.session_id}")

        if await session.browser.initialize_async(BrowserOption()):
            print("Browser initialized successfully")
            endpoint_url = session.browser.get_endpoint_url()
            print("endpoint_url =", endpoint_url)

            async with async_playwright() as p:
                browser = await p.chromium.connect_over_cdp(endpoint_url)
                page = await browser.new_page()
                agent = session.browser.agent

                try:
                    await page.goto("https://www.casetify.cn/", timeout=90000)
                    act_option = ActOptions(
                        action="Click 'All products' button or link",
                    )
                    await agent.act_async(page, act_option)
                    all_extracted_products = []
                    page_count = 1
                    while True:
                        extract_option = ExtractOptions(
                            instruction="Extract all products visible on the current page. For each product, get its name, price, and the complete, absolute URL to its product page.",
                            schema=InspectionResult,
                            use_text_extract=True,
                        )
                        success, page_result = await agent.extract_async(
                            page, extract_option
                        )
                        if success and page_result.products:
                            print(
                                f"  > Found {len(page_result.products)} products on this page."
                            )
                            all_extracted_products.extend(page_result.products)
                        else:
                            print(
                                "  > No products found on this page, continuing to next page check."
                            )

                        print("  > Checking for a 'Next' page button...")
                        act_option = ActOptions(
                            action="Scroll down to the bottom of the page.",
                        )
                        await agent.act_async(page, act_option)

                        act_option = ActOptions(
                            action="Click the 'Next' button or a link that navigates to the next page. This button is often marked with text 'Next', '>', or '→'.",
                        )
                        action_result = await agent.act_async(page, act_option)
                        if action_result and action_result.success:
                            print("  > Successfully navigated to the next page.")
                            page_count += 1
                            await asyncio.sleep(3)
                        else:
                            print(
                                "> Could not find or click a 'Next' button. Reached the last page."
                            )
                            break

                    print("\n--- Final Inspection Report ---")
                    total_products = len(all_extracted_products)
                    print(
                        f"Extraction complete. Scanned {page_count} pages and found a total of {total_products} products."
                    )

                    if all_extracted_products:
                        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                        output_filename = f"/tmp/inspection_results_{timestamp}.json"

                        print(
                            f"\n--- Saving {total_products} products to file: {output_filename} ---"
                        )

                        try:
                            products_as_dicts = [
                                p.model_dump(mode="json")
                                for p in all_extracted_products
                            ]
                            with open(output_filename, "w", encoding="utf-8") as f:
                                json.dump(
                                    products_as_dicts, f, ensure_ascii=False, indent=2
                                )

                            print(f"✅ Successfully saved results to {output_filename}")

                        except Exception as e:
                            print(f"❌ Failed to save results to file: {e}")

                    print("\n✅ Paginated inspection demo finished successfully.")

                    print("\n✅ Paginated inspection demo finished successfully.")

                except Exception as e:
                    print(f"❌ An error occurred during the paginated inspection: {e}")
                finally:
                    session.delete()


if __name__ == "__main__":
    asyncio.run(main())
